﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Reflection;
using Tecnopez.Globals;
using BussinessLogicTecnoPez;
using BussinessLogicTecnoPez.Produccion.Enfermedades_y_control_de_estanques;

public partial class Globals_Search : System.Web.UI.Page
{
    Type classType;
    string IDControl;

    const string viewStateDirection = "viewStateDirection";
    const string viewStateKey = "viewStateKey";

    protected void Page_Load(object sender, EventArgs e)
    {
        string objType = Request["sessionName"];
        grdData.EmptyDataText = "No hay resultados.";
        object seleccion = Session["objElejido" + objType];
        if (seleccion == null)
        {
            Session.Add("objElejido" + objType, null);
            btnQuitarSeleccion.Visible = false;
            lblSeleccion.Visible = false;
            txtSeleccionElement.Visible = false;
        }
        else
        {
            txtSeleccionElement.Text= seleccion.ToString();
            txtSeleccionElement.Visible = true;
            txtSeleccionElement.ReadOnly = true;
            btnQuitarSeleccion.Visible = true;
        }
        IDControl = (string)Request["id"];        
        
        classType = (Type)Session[objType];

        createGridFilters();

        if (this.Page.IsPostBack == false)
        {
            GrdViewInitializator confG = new GrdViewInitializator(this.ViewState, "orden", "ordenDireccion", true, cargarGrilla, classType);

            ButtonField colB = new ButtonField();
            colB.ButtonType = ButtonType.Image;
            colB.ImageUrl = Functions.getHost(this.Page) + "Styles/Icons/next.gif";
            colB.CommandName = "ver";
            ButtonField[] d = new ButtonField[1];
            d[0] = colB;

            confG.gridViewSetup(this.grdData, true, d);
        }
    }

    protected void grdData_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "ver")
        {
            string objType = Request["sessionName"];

            Object auxObj = Activator.CreateInstance(classType);
            MethodInfo[] metodos;
            metodos = classType.BaseType.GetMethods();
            foreach (MethodInfo m in metodos)
            {
                if (m.Name == "get_getManager")
                {
                    Type genericType;
                    genericType = m.Invoke(auxObj, null).GetType();
                    Object auxObjGen = Activator.CreateInstance(genericType);
                    MethodInfo[] metodosGenericos;
                    metodosGenericos = genericType.GetMethods();
                    foreach (MethodInfo gm in metodosGenericos)
                    {
                        if (gm.Name == "ClearFilters")
                        {
                            gm.Invoke(auxObjGen, null);
                        }
                    }

                    foreach (MethodInfo gm in metodosGenericos)
                    {
                        if (gm.Name == "AddFilter")
                        {
                            ParameterInfo[] gmParams = gm.GetParameters();
                            if (gmParams[2].ToString()=="System.Object value")
                            {

                                PropertyInfo[] miembros = classType.GetProperties();
                                foreach (PropertyInfo mi in miembros)
                                {
                                    object[] cusAtt = mi.GetCustomAttributes(false);
                                    foreach (object objca in cusAtt)
                                    {
                                        DBField dbF = objca as DBField;
                                        if (dbF != null)
                                        {
                                            if (dbF.IsKey == true)
                                            {
                                                GenericManager<Object> a = new GenericManager<object>();
                                                int o = int.Parse(e.CommandArgument.ToString());
                                                object[] Parametros = new object[3]
                                                {
                                                    //dbF.Name,
                                                    mi.Name,
                                                    GenericManager<Object>.filterOperator.Equals,
                                                    int.Parse(grdData.DataKeys[o].Value.ToString())
                                                };
                                                gm.Invoke(auxObjGen, Parametros);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    foreach (MethodInfo gm in metodosGenericos)
                    {
                        if (gm.Name == "GetOne")
                        {
                            Session.Add("objElejido" + objType, gm.Invoke(auxObjGen, null));
                        }
                    }
                }
            }


            //Enfermedad aux = new Enfermedad();
            //aux.Nombre = "enfermedad";
            //aux.IdEnfermedad = 123;
            //Session.Add("objElejido", aux);

            string texto="";

            if (Session["objElejido" + objType] != null)
            {
                texto = Session["objElejido" + objType].ToString();
            }

            string strScript;
            string functionId = Request["function"];
            strScript = "window.opener.tomar_" + functionId + "('" + texto + "', '" + IDControl + "');";
            strScript = strScript + "window.close();";
            ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "tomar", strScript, true);
            //this.ClientScript.RegisterClientScriptBlock(this.Page.GetType(), "tomar", strScript,true);
            
        }
    }

    

    public void cargarGrilla()
    {
        string objType = Request["sessionName"];
        object classIns = Activator.CreateInstance(classType);
        object gestorIns = EjecutarFuncionReflectionConRetorno(classType.BaseType,classIns, "get_getManager", null);
        personalizarGestor metodoParaPersonalizar = Session["gestorAntes" + objType] as personalizarGestor;

        if (gestorIns != null)
        {
            Type tipoGestor = gestorIns.GetType();
            if (tipoGestor != null)
            {
                EjecutarFuncionReflection(tipoGestor, gestorIns, "ClearOrders", null);
                EjecutarFuncionReflection(tipoGestor, gestorIns, "ClearFilters", null);
                AddFilters(tipoGestor, gestorIns);
                if (metodoParaPersonalizar != null)
                {
                    metodoParaPersonalizar(gestorIns);
                }
                if (ViewState[viewStateKey] != null)
                {
                    object[] parametros = new object[]
                    {
                        ViewState[viewStateKey].ToString(),
                        (GenericManager<Object>.Order.orderDirection)ViewState[viewStateDirection]
                    };
                    EjecutarFuncionReflection(tipoGestor, gestorIns, "AddOrder", parametros);
                   
                    grdData.DataSource = EjecutarFuncionReflectionConRetorno(tipoGestor, gestorIns, "GetFilter", null);
                    grdData.DataBind();
                }
                else
                {
                   
                    grdData.DataSource = EjecutarFuncionReflectionConRetorno(tipoGestor, gestorIns, "GetFilter", null);
                    grdData.DataBind();
                }
            }
        }
    }

    private object EjecutarFuncionReflectionConRetorno(Type tipoObjeto, object InstanciaObjeto, string metodo, object[] Parametros)
    {
        object res=null;
        MethodInfo[] metodos = tipoObjeto.GetMethods();
        foreach(MethodInfo mi in metodos)
        {
            if(mi.Name==metodo)
            {
                res= mi.Invoke(InstanciaObjeto,Parametros);
            }
        }
        return res;
    }

    private void EjecutarFuncionReflection(Type tipoObjeto, object InstanciaObjeto, string metodo, object[] Parametros)
    {
        try
        {
            MethodInfo[] metodos = tipoObjeto.GetMethods();
            foreach (MethodInfo mi in metodos)
            {
                if (mi.Name == metodo)
                {
                    mi.Invoke(InstanciaObjeto, Parametros);
                }
            }
            lblMensaje.Text = "";
        }
        catch 
        {
            lblMensaje.Text="La columna seleccionada no puede ser usada para ordenar los datos, seleccione otra columna.";
         
        }
    }

    private void createGridFilters()
    {
        string strNameProperty = "";
        string strFriendlyNameProperty = "";
        FriendlyName.FilterType filterType = FriendlyName.FilterType.String;

        TableRow objTR = null;
        TableCell objTC = null;
        TextBox objTxt = null;
        
        PropertyInfo[] miembros = classType.GetProperties();
        foreach (PropertyInfo mi in miembros)
        {
            strNameProperty = "";
            strFriendlyNameProperty = "";

            object[] cusAtt = mi.GetCustomAttributes(false);
            foreach (object objca in cusAtt)
            {
                DBField objDBField = objca as DBField;
                if (objDBField != null)
                {
                    strNameProperty = objDBField.Name;
                }

                FriendlyName objFriendlyName = objca as FriendlyName;
                if (objFriendlyName != null)
                {
                    if (objFriendlyName.ShowFilter == true)
                    {
                        filterType = objFriendlyName.Type;
                        strFriendlyNameProperty = objFriendlyName.myFriendlyName;
                    }
                }
            }
            //si es un campo de la base y se puede filtrar, entonces agrego el filtro
            if (strNameProperty != "" && strFriendlyNameProperty != "")
            {
                objTR = new TableRow();
                objTC = new TableCell();
                objTC.CssClass = "columnaLabels";
                objTC.Text = strFriendlyNameProperty;
                objTR.Cells.Add(objTC);

                objTC = new TableCell();
                objTC.CssClass = "columnaData";
                objTC.Controls.Add(FillDropDownList(filterType));
                objTR.Cells.Add(objTC);

                objTC = new TableCell();
                objTC.CssClass = "columnaData";
                objTxt = new TextBox();
                objTxt.ID = strNameProperty;
                objTxt.EnableViewState = true;
                objTC.Controls.Add(objTxt);
                objTR.Cells.Add(objTC);

                this.tblFiltros.Rows.Add(objTR);
            }
        }
        if (this.tblFiltros.Rows.Count == 0)
            this.btnFiltrar.Visible = false;
        else
        {
            this.tblFiltros.CellPadding = 0;
            this.tblFiltros.CellSpacing = 0;

            this.btnFiltrar.CssClass = "Boton";
        }
    }

    private DropDownList FillDropDownList(FriendlyName.FilterType type)
    {
        DropDownList objDDL= new DropDownList();
        ListItem objItem;
        switch (type)
        {
            case FriendlyName.FilterType.Integer:
                objItem = new ListItem();
                objItem.Text = "Igual";
                objItem.Value = "0";
                objDDL.Items.Add(objItem);

                objItem = new ListItem();
                objItem.Text = "Mayor que";
                objItem.Value = "1";
                objDDL.Items.Add(objItem);

                objItem = new ListItem();
                objItem.Text = "Menor que";
                objItem.Value = "2";
                objDDL.Items.Add(objItem);
                objDDL.SelectedIndex = 0;
                break;
            case FriendlyName.FilterType.String:
                objItem = new ListItem();
                objItem.Text = "Igual";
                objItem.Value = "0";
                objDDL.Items.Add(objItem);

                objItem = new ListItem();
                objItem.Text = "Contiene";
                objItem.Value = "4";
                objDDL.Items.Add(objItem);
                objDDL.SelectedIndex = 1;
                break;
            default:
                objItem = new ListItem("Tipo no especificado");
                objDDL.Items.Add(objItem);
                break;
        }
        return objDDL;
    }

    protected void btnFiltrar_Click(object sender, EventArgs e)
    {        
        GrdViewInitializator confG = new GrdViewInitializator(this.ViewState, "orden", "ordenDireccion", true, cargarGrilla, classType);

        ButtonField colB = new ButtonField();
        colB.ButtonType = ButtonType.Image;
        colB.ImageUrl = Functions.getHost(this.Page) + "Styles/Icons/next.gif";
        colB.CommandName = "ver";
        ButtonField[] d = new ButtonField[1];
        d[0] = colB;

        confG.gridViewSetup(this.grdData, true, d);
    }

    private void AddFilters(Type tipoGestor, object objGestor)
    {
        TextBox objTxt = null;
        DropDownList objDDL = null;

        for (int i = 0; i < this.tblFiltros.Rows.Count; i++)
        {
            objDDL = (DropDownList)this.tblFiltros.Rows[i].Cells[1].Controls[0];
            objTxt = (TextBox)this.tblFiltros.Rows[i].Cells[2].Controls[0];
         //   TipoEstanque.getManager.AddFilter("", GenericManager<TipoEstanque>.filterOperator.Equals, "");
            if (objTxt.Text != "")
            {
                
                //object[] Parametros = new object[3]
                //{
                //    objTxt.ID,
                //    GenericManager<Object>.filterOperator.Equals,
                //    objTxt.Text
                //};

                EjecutarFuncionReflection(tipoGestor, objGestor, "AddFilter", CreateParameters(int.Parse(objDDL.SelectedValue),objTxt));
            }
        }



    }
    private object[] CreateParameters(int filterType, TextBox objTxt)
    {
        object[] Parametros;
        switch (filterType)
        {
            case 0:
                Parametros = new object[3]
                {
                    objTxt.ID,
                    GenericManager<Object>.filterOperator.Equals,
                    objTxt.Text
                };
                return Parametros;
            case 1:
                Parametros = new object[3]
                {
                    objTxt.ID,
                    GenericManager<Object>.filterOperator.BiggerThan,
                    objTxt.Text
                };
                return Parametros;
            case 2:
                Parametros = new object[3]
                {
                    objTxt.ID,
                    GenericManager<Object>.filterOperator.SmallerThan,
                    objTxt.Text
                };
                return Parametros;
            case 4:
                Parametros = new object[3]
                {
                    objTxt.ID,
                    GenericManager<Object>.filterOperator.Like,
                    "%" + objTxt.Text + "%"
                };
                return Parametros;
        }
        return null;
    }
    protected void grdData_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.grdData.PageIndex = e.NewPageIndex;
        GrdViewInitializator confG = new GrdViewInitializator(this.ViewState, "orden", "ordenDireccion", true, cargarGrilla, classType);

        ButtonField colB = new ButtonField();
        colB.ButtonType = ButtonType.Image;
        colB.ImageUrl = Functions.getHost(this.Page) + "Styles/Icons/next.gif";
        colB.CommandName = "ver";
        ButtonField[] d = new ButtonField[1];
        d[0] = colB;

        confG.gridViewSetup(this.grdData, true, d);
    }
    protected void grdData_Sorting(object sender, GridViewSortEventArgs e)
    {
        GenericManager<Object>.Order.orderDirection direccion;
        if (ViewState[viewStateDirection] != null)
        {
            direccion = (GenericManager<Object>.Order.orderDirection)ViewState[viewStateDirection];
            if (direccion == GenericManager<Object>.Order.orderDirection.ASC && ViewState[viewStateKey].ToString() == e.SortExpression)
            {
                direccion = GenericManager<Object>.Order.orderDirection.DESC;
            }
            else
            {
                direccion = GenericManager<Object>.Order.orderDirection.ASC;
            }
        }
        else
        {
            direccion = GenericManager<Object>.Order.orderDirection.ASC;
        }
        ViewState.Add(viewStateKey, e.SortExpression);
        ViewState.Add(viewStateDirection, direccion);

        GrdViewInitializator confG = new GrdViewInitializator(this.ViewState, "orden", "ordenDireccion", true, cargarGrilla, classType);

        ButtonField colB = new ButtonField();
        colB.ButtonType = ButtonType.Image;
        colB.ImageUrl = Functions.getHost(this.Page) + "Styles/Icons/next.gif";
        colB.CommandName = "ver";
        ButtonField[] d = new ButtonField[1];
        d[0] = colB;

        confG.gridViewSetup(this.grdData, true, d);
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string objType = Request["sessionName"];
        string texto = "";

        Session.Remove("objElejido" + objType);
        

        string strScript;
        string functionId = Request["function"];
        strScript = "window.opener.tomar_" + functionId + "('" + texto + "', '" + IDControl + "');";
        strScript = strScript + "window.close();";
        ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "tomar", strScript, true);
    }
}
